package com.base.vistter.iframe.advice;

import com.base.vistter.iframe.bean.Result;
import com.base.vistter.iframe.menu.ErrorLoginEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(BindException.class)
    public Result<String> bindExceptionHandler(BindException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        return Result.error(fieldErrors.get(0).getDefaultMessage());
    }

    /**
     * 表单验证失败后触发的函数
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        return Result.error(fieldErrors.get(0).getDefaultMessage());
    }

    /**
     * 登录账号找不到
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<String> usernameNotFoundExceptionHandler(UsernameNotFoundException e) {
        return Result.error(ErrorLoginEnum.USERNAME_OR_PASSPWRD_ERROR);
    }

    /**
     * 登录凭证错误
     */
    @ExceptionHandler(BadCredentialsException.class)
    public Result<String> badCredentialsExceptionHandler(BadCredentialsException e) {
        return Result.error(ErrorLoginEnum.USERNAME_OR_PASSPWRD_ERROR);
    }

    @ExceptionHandler(LockedException.class)
    public Result<String> lockedExceptionHandler(LockedException e) {
        return Result.error(ErrorLoginEnum.USERNAME_ISSTOP);
    }

    /**
     * 统一错误处理
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handle(Exception e){
        return Result.error(e.getMessage());
    }

}
